Fix type narrowing with not isinstance(x, cls) in classmethods#21312
Open
sanyamk23 wants to merge 3 commits intopython:masterfrom
Open
Fix type narrowing with not isinstance(x, cls) in classmethods#21312sanyamk23 wants to merge 3 commits intopython:masterfrom
sanyamk23 wants to merge 3 commits intopython:masterfrom
Conversation
Adjust get_type_range_of_type to set is_upper_bound=False for Self types, allowing precise narrowing in negative checks. Fixes python#21271.
Contributor
|
Diff from mypy_primer, showing the effect of this PR on open source code: comtypes (https://github.com/enthought/comtypes)
+ comtypes/_post_coinit/unknwn.py:347: error: Unused "type: ignore" comment [unused-ignore]
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Adjust get_type_range_of_type to set is_upper_bound=False for Self types, allowing precise narrowing in negative checks. Fixes #21271.
Description
This PR addresses an issue where
not isinstance(x, cls)inside a@classmethodfailed to correctly narrow the type ofxwhen it involvedSelf.In
mypy/checker.py,get_type_range_of_typewas conservatively settingis_upper_bound=Truefor allTypeTypeobjects (likecls: Type[Self]). This prevented the narrowing logic from removingSelffrom a union in theelsebranch, as it assumed the check wasn't precise.This change sets
is_upper_bound=Falsespecifically forSelftypes (and also handlesNoneTypeand final classes similarly). This allowsmypyto correctly narrowxto the remaining types in the union when theisinstance(x, cls)check fails.Checklist